package sf.tools.reflect;

import sf.tools.reflect.typeref.BooleanType;
import sf.tools.reflect.typeref.ByteType;
import sf.tools.reflect.typeref.CharType;
import sf.tools.reflect.typeref.DoubleType;
import sf.tools.reflect.typeref.FloatType;
import sf.tools.reflect.typeref.IntType;
import sf.tools.reflect.typeref.LongType;
import sf.tools.reflect.typeref.ShortType;
import sf.tools.reflect.typeref.UnsafeTypeInf;

import java.util.HashMap;
import java.util.Map;

public class UnsafeGetUtils {

    private static Map<Class<?>, UnsafeTypeInf> typeMap = new HashMap<>();

    static {
        typeMap.put(byte.class, new ByteType());
        typeMap.put(boolean.class, new BooleanType());
        typeMap.put(char.class, new CharType());
        typeMap.put(short.class, new ShortType());
        typeMap.put(int.class, new IntType());
        typeMap.put(long.class, new LongType());
        typeMap.put(float.class, new FloatType());
        typeMap.put(double.class, new DoubleType());
    }


    public final static <T> T getValue(Object obj, long fieldOffset, Class<T> valueClz) {
        Object value;
        UnsafeTypeInf typeInf = typeMap.get(valueClz);
        if (typeInf != null) {
            value = typeInf.getValue(obj, fieldOffset);
        } else {
            value = UnsafeUtils.getUnsafe().getObject(obj, fieldOffset);
        }
        return (T) value;
    }
}
